package violin.web;

import violin.Configuration;

import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

public class Site {
    private final Configuration configuration;
    private final Set<Resource> resourcePool;
    private static final Resource NOTFOUND = new Resource("/", null);

    public Site(Configuration configuration) {
        this.configuration = configuration;
        this.resourcePool = new HashSet<Resource>();
    }

    public void bind(Class<?> resourceClass) {
        String path;
        if (resourceClass.isAnnotationPresent(Path.class)) {
            path = resourceClass.getAnnotation(Path.class).value();
        } else {
            path = configuration.getResourcePath(resourceClass);
        }
        resourcePool.add(new Resource(path, resourceClass));
    }

    Resource locate(String uri) {
        String path = uri.startsWith("/") ? uri.substring(1) : uri;
        for (Resource resource : resourcePool) {
            if (resource.matches(path)) {
                return resource;
            }
        }
        return NOTFOUND;
    }

}
